/*
 * @Author: wangqizhang
 * @Date: 2024-04-23 16:05:33
 * @LastEditors: wangqizhang
 * @LastEditTime: 2024-04-23 16:37:18
 * @FilePath: /suixinji/src/hooks/loading/index.ts
 * @Description:
 *
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved.
 */
//声明Loading类需要的参数类型
type LoadingParams = {
  message: string; //描述
  createNode: HTMLElement; //挂载的daom
  delay: number; //延时执行
};
//声明参数类
class Loading {
  message: string;
  createNode: HTMLElement;
  wrapper: any;
  startTime: number;
  delay: number;
  constructor(parameters: LoadingParams) {
    const { message, createNode, delay } = parameters;
    createNode.style.position = 'relative';
    this.message = message;
    this.createNode = createNode;
    this.wrapper = void 0;
    this.startTime = 0;
    this.delay = delay;
  }
  //创建dom
  init() {
    const wrapper = document.createElement('div');
    wrapper.className = 'loading-wrapper';
    const loadingDom = document.createElement('div');
    loadingDom.className = 'loader';
    const messagDom = document.createElement('div');
    messagDom.innerHTML = this.message;
    wrapper.appendChild(loadingDom);
    wrapper.appendChild(messagDom);
    this.wrapper = wrapper;
  }
  //动画开始
  start() {
    this.init();
    this.createNode.appendChild(this.wrapper);
    this.startTime = Date.now();
  }
  //动画结束
  stop() {
    if (this.wrapper) {
      let delayTimer = Date.now() - this.startTime;
      if (delayTimer > this.delay) {
        this.createNode.removeChild(this.wrapper);
      } else {
        setTimeout(() => {
          this.createNode.removeChild(this.wrapper);
        }, this.delay - delayTimer);
      }
    }
  }
}
//导出hooks函数
export const useLoading = (
  params: LoadingParams = {
    message: '加载中',
    createNode: document.body,
    delay: 500,
  }
) => {
  const loading = new Loading(params);
  return {
    start: () => {
      loading.start();
    },
    stop: () => {
      loading.stop();
    },
  };
};
